<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2016-2018 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w [y139w@163.com]
 * +--------------------------------------------------------------
 * | 分页类文件
 * +--------------------------------------------------------------
 */

namespace luo;


class Page{

    /**
     * 总页数
     * @var int
     */
    private $total;

    /**
     * 当前页
     * @var int
     */
    private $cur;

    /**
     * 中间几页
     * @var int
     */
    private $leaf;

    /**
     * Pages constructor.
     * @param $current
     * @param $total
     */
    public function __construct($current,$total){
        $this->total = $total;
        $this->cur   = $current;
        $this->leaf  = 5;
    }

    /**
     * 设置中间有几页
     * @param int $leaf
     * @return $this
     */
    public function setLeaf($leaf = 5){
        $this->leaf = $leaf;
        return $this;
    }

    /**
     * 处理下一页
     * @return int
     */
    private function _next(){
        $next = $this->cur + 1;
        if($next >= $this->total){
            $next = $this->total;
        }
        return $next;
    }

    /**
     * 处理上一页
     * @return int
     */
    private function _prev(){
        $prev = $this->cur - 1;
        if($prev <= 1){
            $prev = 1;
        }
        return $prev;
    }

    /**
     * 中间几页处理
     * @return array
     */
    private function _leaf(){

        $deviation = ($this->leaf - 1) / 2;   //偏移量
        $remain    = ($this->leaf - 1) % 2;   //求余数
        $left      = $deviation;
        $right     = $deviation + $remain;

        $lt = $this->cur - $left;

        $rt = $this->cur + $right;

        if($lt <= 1){
            $lt = 1;
            $rt = $this->leaf - $lt + 1;
        }
        if($rt >= $this->total){
            $rt = $this->total;
            $lt = $this->cur - ($this->leaf - ($this->total - $this->cur)) + 1;
            if($lt <= 1){
                $lt = 1;
            }
        }
        $leafArr = array();
        for($i = $lt ; $i <= $rt; $i++){
            $leafArr[] = $i;
        }

        return $leafArr;
    }

    /**
     * 获取处理结果
     * @return array
     */
    public function show(){
        $pages = array(
            'total'   => $this->total,
            'current' => $this->cur,
            'prev'    => $this->_prev(),
            'next'    => $this->_next(),
            '_leaf'    => $this->leaf,
            'leaf'    => $this->_leaf()
        );
        return $pages;
    }

}